<template>
    <el-card>
        部门名称
        <el-input v-model="form.departName" />
        <el-button type="primary" @click="GetList()">查询</el-button>
        <el-button type="primary" @click="Add()">添加部门</el-button>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="departName" label="部门名称" align="center" />
            <el-table-column prop="status" label="状态" align="center">
                <template v-slot="scope">
                    <span v-if="scope.row.status === true">启用</span>
                    <span v-else>禁用</span>
                </template>
            </el-table-column>
            <el-table-column prop="memberCount" label="成员数量" align="center" />
            <el-table-column prop="userName" label="主管人员" align="center" />
            <el-table-column prop="description" label="部门描述" align="center" />
            <el-table-column prop="updateTime" label="更新时间" align="center">
                <template #default="scope">

                    {{ scope.row.updateTime.substring(0, 10).split('T')[0] }}
                </template>
            </el-table-column>
            <el-table-column prop="order" label="排序" align="center" />
            <el-table-column label="操作" align="center">
                <template v-slot="scope">
                    <el-button type="primary" size="small" @click="FanDepartment(scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="DelPartMent(scope.row)">删除</el-button>
                    <el-button type="primary" plain size="small" @click="statustann(scope.row)">设置状态</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <el-dialog v-model="AdddialogVisible" :title="AddTips" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="部门名称" prop="departName">
                <el-input v-model="ruleForm.departName" />
            </el-form-item>

            <el-form-item label="上级部门" prop="parentId">
                <el-cascader v-model="ruleForm.parentId" :options="departEdit" :props="props"
                    clearable:show-all-levels="false" />
            </el-form-item>


            <el-form-item label="主管人员" prop="userId">
                <el-select v-model="ruleForm.userId" placeholder="请选择主管人员">
                    <el-option v-for="item in userlist" :label="item.userName" :value="item.userId" />
                </el-select>
            </el-form-item>

            <el-form-item label="部门描述" prop="description">
                <el-input v-model="ruleForm.description" type="textarea" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <el-dialog v-model="UpdatedialogVisible" :title="UpdateTips" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="部门名称" prop="departName">
                <el-input v-model="ruleForm.departName" />
            </el-form-item>

            <el-form-item label="上级部门" prop="parentId">
                <el-cascader v-model="ruleForm.parentId" :options="departEdit" :props="props"
                    clearable:show-all-levels="false" />
            </el-form-item>


            <el-form-item label="主管人员" prop="userId">
                <el-select v-model="ruleForm.userId" placeholder="请选择主管人员">
                    <el-option v-for="item in userlist" :label="item.userName" :value="item.userId" />
                </el-select>
            </el-form-item>

            <el-form-item label="部门描述" prop="description">
                <el-input v-model="ruleForm.description" type="textarea" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="UpdateDepartment(ruleFormRef)">
                    修改
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>



    <el-dialog v-model="statusdialogVisible" title="设置状态" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="部门名称" prop="departName">
                <el-input v-model="ruleForm.departName" />
            </el-form-item>

            <el-form-item label="选择状态">
                <el-radio-group v-model="ruleForm.status">
                    <el-radio-button :label="true">启用</el-radio-button>
                    <el-radio-button :label="false">禁用</el-radio-button>
                </el-radio-group>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="updstatus()">
                    修改
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>



</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'
import { de, fa } from 'element-plus/es/locales.mjs';
import { departlist, selectUser, selectDeptMenu, departAdd, delpartmentid, updatedepartmet, updatepartmentstatus } from '@/assets/api/depart';


const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    "departId": 0,
    "departName": "",
    "parentId": 0,
    "userId": 0,
    "description": "暂无相关描述",
    "status": false,
    "memberCount": 100,
    "order": null,
    "updateTime": "2024-04-04T00:00:00",
    "isDeleted": false
})
const form = reactive({
    departName: '',
})
const page = reactive({
    pageIndex: 1,
    pageSize: 10,
    totalCount: 0,
    totalPage: 0,
})


var tableData = ref([])
const GetList = async () => {

    var params = {
        pageIndex: page.pageIndex,
        pageSize: page.pageSize,
        departName: form.departName
    }


    const reponse = await departlist(params)
    tableData.value = reponse.data.data.data
    page.totalCount = reponse.data.data.totalCount
    page.totalPage = reponse.data.data.totalPage

}

onMounted(() => {
    selectuserlist();
    selectDeptMenuList();
    GetList();
})

let userlist = ref([{
    userId: 0,
    userName: ""
}]);

const selectuserlist = async () => {
    await selectUser().then(res => {
        userlist.value = res.data.data
        ruleForm.userId = res.data.data.userId
    })
}

var AdddialogVisible = ref(false)
const AddTips = ref('添加页面')
const Add = () => {
    AdddialogVisible.value = true
}

const rules = reactive<FormRules>({
    departName: [
        { required: true, message: '部门名称不能为空', trigger: 'blur' },
    ],
    parentId: [
        {
            required: true,
            message: '请选择上级部门',
            trigger: 'change',
        },
    ],
    userId: [
        {
            required: true,
            message: '请选择上级部门',
            trigger: 'change',
        },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            await departAdd(ruleForm).then((res) => {
                if (res.data.code == 0) {

                    ElMessage.success("添加成功")
                    AdddialogVisible.value = false
                    GetList();
                } else {
                    ElMessage({
                        message: res.data.msg,
                        type: 'error',
                    })
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}


const props = {
    checkStrictly: true,
    emitPath: false
}
let departEdit = ref([])
const selectDeptMenuList = async () => {
    await selectDeptMenu()
        .then(res => {
            departEdit.value = res.data.data
        })
}

const DelPartMent = (row: any) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const respnse = await delpartmentid(row.departId)
            if (respnse.data.code == 0) {
                ElMessage.success("删除成功");
                GetList();
            }
            else {
                ElMessage.error("删除失败");
                return;
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        })
}

var UpdatedialogVisible = ref(false);
var UpdateTips = ('修改页面');

const FanDepartment = (row: any) => {
    UpdatedialogVisible.value = true;
    ruleForm.departId = row.departId,
        ruleForm.departName = row.departName,
        ruleForm.parentId = row.parentId,
        ruleForm.userId = row.userId,
        ruleForm.description = row.description


}
// 新建部门表单ref
const newDeptFormRef = ref<FormInstance>()

// 关闭新建部门对话框时重置表单和校验状态
const resetNewDeptForm = () => {
    ruleForm.departId = 0;
    ruleForm.departName = '';
    ruleForm.parentId = 0;


    if (newDeptFormRef.value) {
        newDeptFormRef.value.resetFields(); // 重置表单校验状态
    }
};
const UpdateDepartment = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            await updatedepartmet(ruleForm).then((res) => {
                console.log(res);
                if (res.data.code == 0) {
                    ElMessage.success("修改成功");
                    UpdatedialogVisible.value = false;
                    GetList();
                } else {
                    ElMessage({
                        message: res.data.msg,
                        type: 'error',
                    })
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}


//设置角色状态
const statusdialogVisible = ref(false)

const statustann = (row: any) => {
    statusdialogVisible.value = true;
    ruleForm.departId = row.departId;
    ruleForm.departName = row.departName;
    ruleForm.status = row.status;
}

//设置角色状态效果
const updstatus = async () => {
    await updatepartmentstatus(ruleForm.departId, ruleForm.status)
        .then((res: any) => {
            if (res.data.code == 0) {
                ElMessage.success("状态设置成功");
                statusdialogVisible.value = false; // 保存成功后关闭弹窗
                GetList() // 刷新列表
            }
            else {
                ElMessage.error(res.data.message)
            }
        })
        .catch((error: any) => {
            console.error('设置部门状态失败:', error)
            ElMessage.error('网络错误，请稍后再试');
        })
}

</script>

<style scoped></style>